<template>
  <div class="park-management-container">
    <!-- 内容标签页 -->
    <el-tabs v-model="activeTab" class="content-tabs" @tab-remove="handleTabRemove" type="card">
      <!-- 园区列表标签页 - 默认显示 -->
      <el-tab-pane label="园区信息" name="park">
        <ParkList @view-buildings="handleViewBuildings" @view-park="handleView" ref="ParkListRef" />
      </el-tab-pane>

      <el-tab-pane v-for="tab in parkViewTabs" :key="tab.id" :label="tab.label" :name="tab.name" :closable="true">
        <ParkSpace :park-id="tab.parkId" :park-name="tab.parkName" />
      </el-tab-pane>

      <!-- 动态生成的楼栋标签页 -->
      <el-tab-pane v-for="tab in buildingTabs" :key="tab.id" :label="tab.label" :name="tab.name" :closable="true">
        <BuildingList :park-id="tab.parkId" :park-name="tab.parkName" @view-rooms="handleViewRooms"
          :ref="(el) => { if (el) buildingListRefs[tab.parkId] = el }" />
      </el-tab-pane>

      <!-- 动态生成的房间标签页 -->
      <el-tab-pane v-for="tab in roomTabs" :key="tab.id" :label="tab.label" :name="tab.name" :closable="true">
        <RoomList :building-id="tab.buildingId" :building-name="tab.buildingName" :building-floors="tab.buildingFloors"
          :ref="(el) => { if (el) roomListRefs[tab.buildingId] = el }" />
      </el-tab-pane>
    </el-tabs>

    <!-- 表单弹窗 -->
    <ParkForm ref="parkFormRef" :visible="parkFormVisible" :form-data="parkFormData" @close="parkFormVisible = false"
      @save="handleParkSave" />

    <BuildingForm ref="buildingFormRef" :visible="buildingFormVisible" :form-data="buildingFormData"
      @close="buildingFormVisible = false" @save="handleBuildingSave" />

    <RoomForm ref="roomFormRef" :visible="roomFormVisible" :form-data="roomFormData" @close="roomFormVisible = false"
      @save="handleRoomSave" />

    <BatchRoomForm ref="batchRoomFormRef" @success="handleBatchRoomSuccess" />
  </div>
</template>

<script setup>
import { ref, provide, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import ParkList from './ParkList.vue';
import BuildingList from './BuildingList.vue';
import ParkSpace from './view/ParkSpace.vue';
import RoomList from './RoomList.vue';
import ParkForm from './tools/ParkForm.vue';
import BuildingForm from './tools/BuildingForm.vue';
import RoomForm from './tools/RoomForm.vue';
import BatchRoomForm from './tools/BatchRoomForm.vue';
import request from '@/api/request'



// 状态管理
const activeTab = ref('park');
const parkFormVisible = ref(false);
const buildingFormVisible = ref(false);
const roomFormVisible = ref(false);
const parkFormData = ref({});
const buildingFormData = ref({});
const roomFormData = ref({});

// 标签页管理
const parkViewTabs = ref([]);
const buildingTabs = ref([]);
const roomTabs = ref([]);

// 数据存储
const parkData = reactive([]);
const buildingData = reactive([]);
const roomData = reactive([]);


// 提供数据和方法供子组件使用
provide('parkData', parkData);
provide('buildingData', buildingData);
provide('roomData', roomData);

// 提供获取列表的方法
provide('fetchParkList', (queryParams, currentPage, pageSize) => {
  let params;
  if (queryParams) {
    params = {
      name: queryParams.name,
      city: queryParams.city,
      pageNum: currentPage,
      pageSize: pageSize
    }
  } else {
    params = {
      pageNum: currentPage,
      pageSize: pageSize
    }
  }
  return new Promise(resolve => {
    request.get('park/page', {
      params: params
    }).then(data => {
      // 假设后端返回格式：{ list: [...园区数据...], total: 100 }
      // 直接替换 parkData 的内容（保持响应式）
      // parkData.splice(0, parkData.length, ...data.list);
      // 同时将数据返回给子组件
      if (data.success) {
        resolve(data.data);
      }
    }).catch(error => {
      parkData.length = 0; // 出错时清空数据
    });
  });
});

provide('fetchBuildingList', (parkId, queryParams, currentPage, pageSize) => {
  return new Promise(resolve => {
    request.get('park-building/page', {
      params: {
        parkId: parkId,
        name: queryParams.name,
        type: queryParams.type,
        pageNum: currentPage,
        pageSize: pageSize
      }
    }).then(data => {
      if (data.success) {
        resolve(data.data);
      } 

    }).catch(error => {
      console.error('获取园区数据失败：', error);
      parkData.length = 0; // 出错时清空数据
    });
  });
});

provide('fetchRoomList', (buildingId, queryParams, currentPage, pageSize) => {
  return new Promise(resolve => {
    request.get('parkRoom/page', {
      params: {
        buildingId: buildingId,
        status: queryParams.status,
        roomNumber: queryParams.roomNumber,
        pageNum: currentPage,
        pageSize: pageSize,
        floor:queryParams.floors
      }
    }).then(data => {
      if (data.success) {
        resolve(data.data);
      } 
    }).catch(error => {
      console.error('获取园区数据失败：', error);
      parkData.length = 0; // 出错时清空数据
    });
  });
});


// 表单提交成功后的处理函数
const handleFormSubmitSuccess = (param, parkOrRoomId) => {
  if (param == "parkList") {
    ParkListRef.value.loadParkList()
  } else if (param == "parkBuildingList") {
    // 检查实例是否存在
    if (buildingListRefs.value[parkOrRoomId]) {
      // 调用方法
      buildingListRefs.value[parkOrRoomId].loadBuildingList();
    }
  } else if (param == "parkRoomList") {
    // 检查实例是否存在
    if (roomListRefs.value[parkOrRoomId]) {
      // 调用方法
      roomListRefs.value[parkOrRoomId].loadRoomList();
    }
  }

};

// 提供打开表单的方法
provide('openParkForm', (data = {}) => {
  if (parkFormRef.value) {
    parkFormRef.value.open(data, handleFormSubmitSuccess)
  } else {
    ElMessage.error("打开弹框失败")
  }
});

provide('openBuildingForm', (data = {}) => {
  if (buildingFormRef.value) {
    buildingFormRef.value.open(data, handleFormSubmitSuccess)
  } else {
    ElMessage.error("打开弹框失败")
  }
});

provide('openRoomForm', (data = {}) => {
  if (roomFormRef.value) {
    roomFormRef.value.open(data, handleFormSubmitSuccess)
  } else {
    ElMessage.error("打开弹框失败")
  }
});

provide('openBatchRoomForm', (building) => {
  batchRoomFormRef.value.open(building, handleFormSubmitSuccess);
});

// 引用
const ParkListRef = ref(null);
// 存储所有子组件实例的对象，key 为 tab.id
const buildingListRefs = ref({});
const roomListRefs = ref({});
const parkFormRef = ref(null);
const buildingFormRef = ref(null);
const roomFormRef = ref(null);
const batchRoomFormRef = ref(null);

// 处理查看楼栋
const handleViewBuildings = (park) => {
  // 检查是否已存在该园区的楼栋标签
  const existingTab = buildingTabs.value.find(tab => tab.parkId === park.id);

  if (existingTab) {
    // 切换到已存在的标签
    activeTab.value = existingTab.name;
  } else {
    // 创建新标签
    const newTab = {
      id: `building-${park.id}`,
      name: `building-${park.id}`,
      label: `${park.name} - 楼栋`,
      parkId: park.id,
      parkName: park.name
    };

    buildingTabs.value.push(newTab);
    activeTab.value = newTab.name;
  }
};

const handleView = (park)=>{
// 检查是否已存在该园区的楼栋标签
  const existingTab = parkViewTabs.value.find(tab => tab.parkId === park.id);

  if (existingTab) {
    // 切换到已存在的标签
    activeTab.value = existingTab.name;
  } else {
    // 创建新标签
    const newTab = {
      id: `parkView-${park.id}`,
      name: `parkView-${park.id}`,
      label: `${park.name} - 地理信息`,
      parkId: park.id,
      parkName: park.name
    };

    parkViewTabs.value.push(newTab);
    activeTab.value = newTab.name;
  }
}

// 处理查看房间
const handleViewRooms = (building) => {
  // 检查是否已存在该楼栋的房间标签
  const existingTab = roomTabs.value.find(tab => tab.buildingId === building.id);

  if (existingTab) {
    // 切换到已存在的标签
    activeTab.value = existingTab.name;
  } else {
    // 创建新标签
    const newTab = {
      id: `room-${building.id}`,
      name: `room-${building.id}`,
      label: `${building.name} - 房间`,
      buildingId: building.id,
      buildingName: building.name,
      buildingFloors: building.floors
    };

    roomTabs.value.push(newTab);
    activeTab.value = newTab.name;
  }
};

// 处理标签移除
const handleTabRemove = (name) => {
  // 移除楼栋标签
  if (name.startsWith('building-')) {
    buildingTabs.value = buildingTabs.value.filter(tab => tab.name !== name);
  } else if (name.startsWith('parkView-')) {
    parkViewTabs.value = parkViewTabs.value.filter(tab => tab.name !== name);
  }
  // 移除房间标签
  else if (name.startsWith('room-')) {
    roomTabs.value = roomTabs.value.filter(tab => tab.name !== name);
  }

  // 如果移除的是当前激活的标签，切换到园区标签
  if (activeTab.value === name) {
    activeTab.value = 'park';
  }
};

// 处理园区保存
const handleParkSave = () => {
  parkFormVisible.value = false;
};

// 处理楼栋保存
const handleBuildingSave = () => {
  buildingFormVisible.value = false;
};

// 处理房间保存
const handleRoomSave = () => {
  roomFormVisible.value = false;
};

// 处理批量生成房间成功
const handleBatchRoomSuccess = () => {
  // 可以在这里刷新房间列表
};
</script>

<style scoped>
.park-management-container {
  padding: 10px;
  background-color: #f5f7fa;
}

.content-tabs {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>
